//
//  MessageListVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/6.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "MessageListVC.h"
#import "MessageListTableViewCell.h"
#import "EaseMessageViewController.h"
#import "MessageListModel.h"
#import "DecryptOrderDetailVC.h"
#import "HelpDetailVC.h"
#import "BuyDecryptOrderDetailVC.h"
#import "BuyInsuredOrderDetailVC.h"
#import "BuyOrderModel.h"
#import "InsuredOrderDetailVC.h"
#import "UITableView+Empty.h"

@interface MessageListVC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;
@property (copy, nonatomic)  NSString *typeStr;
@end

@implementation MessageListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    switch (self.messageType) {
        case 1:
        {
            self.navigationItem.title = @"求助消息";
            self.typeStr = @"MESSAGE_TYPE_CANDIDATE";
        }
            break;
        case 2:
        {
            self.navigationItem.title = @"同事专属消息";
            self.typeStr = @"MESSAGE_TYPE_INCUMBENT";
        }
            break;
        case 3:
        {
            self.navigationItem.title = @"通知消息";
            self.typeStr = @"MESSAGE_TYPE_SYSTEM";
        }
            break;
        default:
            break;
    }
    
    
    [self loadTabbleView];
    [self downRefreshRequest];
    [self upRefreshRequest];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

/*
 方法描述:
 加载列表
 
 参数说明:
 <#参数说明#>
 
 返回结果:
 <#返回结果#>
 
 */
-(void)loadTabbleView{
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageListTableViewCell" bundle:nil] forCellReuseIdentifier:@"MessageListTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}
#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrData.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 65;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *identifier = @"MessageListTableViewCell";
    MessageListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    MessageListModel *model = self.arrData[indexPath.row];
    if (model.relatedUserNickname.length > 0) {
        cell.nameLabel.text = model.relatedUserNickname;
    }else{
        cell.nameLabel.text = @" ";
    }
    if (model.content.length > 0) {
        cell.messageDetailLabel.text = model.content;
    }else{
        cell.messageDetailLabel.text = @" ";
    }
    cell.timeLabel.text = model.createTime;
    if (model.isRead) {
        cell.unreadLabel.hidden = YES;
    }else{
        cell.unreadLabel.hidden = NO;
    }
    if (self.messageType == 3) {
        cell.nameLabel.text = @"通知消息";
        cell.headImagView.image = IMAGE(@"ic_tongzhixiaoxi");
    }else{
        [cell.headImagView sd_setImageWithURL:[NSURL URLWithString:ImageURL(model.relatedUserHeadImg)] placeholderImage:IMAGE(@"默认图")];
    }

    return cell;
    
}


- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    /**消息已读*/
   __block MessageListModel *model = self.arrData[indexPath.row];
    
    [YJMSendRequest postDataWithParameters:@{@"messageId":[NSNumber numberWithInteger:model.messageId]} url:@"user/updateUserMessageReadStatus" result:^(NSDictionary *result, NSError *error) {
        model.isRead = YES;
        [self.tableView reloadData];
    }];
    if ([model.relatedServiceType isEqualToString:@"GOODS_TYPE_WD"]) {
        /**问答*/
        HelpDetailVC *vc = [[HelpDetailVC alloc]init];
        vc.relatedId = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.relatedServiceType isEqualToString:@"GOODS_TYPE_TT"]) {
        /**偷听*/
        HelpDetailVC *vc = [[HelpDetailVC alloc]init];
        vc.relatedId = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.relatedServiceType isEqualToString:@"GOODS_TYPE_JM"]) {
        /**解密*/
        if ([model.messageType isEqualToString:@"MESSAGE_TYPE_INCUMBENT"]) {
            /**同事订单*/
            DecryptOrderDetailVC *vc = [[DecryptOrderDetailVC alloc]init];
            vc.relatedId = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            /**购买订单*/
            BuyDecryptOrderDetailVC *vc = [[BuyDecryptOrderDetailVC alloc]init];
            vc.relatedId = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if ([model.relatedServiceType isEqualToString:@"GOODS_TYPE_BG"]) {
        /**保过*/
        if ([model.messageType isEqualToString:@"MESSAGE_TYPE_INCUMBENT"]) {
            /**同事订单*/
            InsuredOrderDetailVC *vc = [[InsuredOrderDetailVC alloc]init];
            vc.order_id = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            /**购买订单*/
            BuyInsuredOrderDetailVC *vc = [[BuyInsuredOrderDetailVC alloc]init];
            vc.order_id = [NSString stringWithFormat:@"%zd",model.relatedServiceId];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}
#pragma mark -
#pragma mark 下拉刷新
- (void)downRefreshRequest //内部方法改
{
    __weak typeof(self) weakSelf = self;
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        weakSelf.page = kStartPage;
        [YJMSendRequest postDataWithParameters:@{@"type":self.typeStr,@"pageSize":kNumOfPageSize,@"pageNo":[NSNumber numberWithInteger:weakSelf.page]} url:@"user/getUserMessage" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                self.arrData = [NSMutableArray arrayWithArray:[MessageListModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"list"]]];
                if (weakSelf.arrData.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];

                }else{
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
                [weakSelf.tableView.mj_header endRefreshing];
                
            }else{
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            if (self.arrData.count == 0) {
                [weakSelf.tableView noDataAddEmptyUIWithImageName:@"pic_emptystate_two" andEmptyText:@"暂无相关数据" andTopDistance:130];
                self.tableView.tableFooterView = nil;
            } else {
                [weakSelf.tableView haveDataRemoveEmptyUI];
            }
            [weakSelf.tableView reloadData];
        }];
    }];
    MJHEADER;
    
    
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark 上拉加载
- (void)upRefreshRequest //内部方法改
{
    __weak typeof(self) weakSelf = self;
    
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [YJMSendRequest postDataWithParameters:@{@"type":self.typeStr,@"pageSize":kNumOfPageSize,@"pageNo":[NSNumber numberWithInteger:weakSelf.page]} url:@"user/getUserMessage" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                NSArray *arrTemp = [MessageListModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"list"]];
                [self.arrData addObjectsFromArray:arrTemp];
                if (arrTemp.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];

                }else{
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
                [weakSelf.tableView.mj_header endRefreshing];
                
            }else{
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            if (self.arrData.count == 0) {
                [weakSelf.tableView noDataAddEmptyUIWithImageName:@"pic_emptystate_two" andEmptyText:@"暂无相关数据" andTopDistance:130];
                self.tableView.tableFooterView = nil;
            } else {
                [weakSelf.tableView haveDataRemoveEmptyUI];
            }
            [weakSelf.tableView reloadData];
        }];
    }];
    
    MJFOOTER;
    self.tableView.mj_footer = footer;
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)doBack:(id)sender{
    [super btnBackClicked:sender];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMessage" object:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
